package com.tbruyelle.rxpermissions2.harmony;

import com.tbruyelle.rxpermissions2.RxPermissions;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;

public class MainAbility extends FractionAbility {
    private Disposable mDisposable;
    private RxPermissions mRxPermissions;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mRxPermissions = new RxPermissions(this);
        findComponentById(ResourceTable.Id_request_read_user_storage_permission)
                .setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        mDisposable = mRxPermissions.request("ohos.permission.READ_USER_STORAGE")
                                .subscribe(new Consumer<Boolean>() {
                                    @Override
                                    public void accept(Boolean result) throws Exception {
                                        ToastUtil.toast(getContext(), "是否允许：" + result);
                                    }
                                });
                    }
                });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        if (mRxPermissions != null) {
            mRxPermissions.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        }
    }
}
